'use strict'

const { Service } = require('egg')

class UserService extends Service {
  async find (table, name) {
    const {
      ctx
    } = this
    const result = await ctx.model[table].findOne({
      where: {
        user_name: name
      }
    })
    return result
  }

  async create (user) {
    const {
      ctx
    } = this
    return await ctx.model.UsersH5.create(user)
  }

  /**
   * 注册
   * @param {*} 用户信息 
   * @returns 
   */
  async register ({
    username,
    password
  }) {
    const {
      ctx,
      app
    } = this
    const user = await this.find('UsersH5', username)
    let result = {
      code: 200,
      msg: ''
    }
    if (user) {
      result.code = 403
      result.msg = `${username}已经被注册啦`
    } else {
      const encryptPassword = ctx.helper.handleEnCrypt(password, app.config.security.cryptoKey) // 密码加密
      const res = await this.create({
        user_name: username,
        password: encryptPassword
      })
      result.msg = '注册成功'
      result.data = {
        username: res.user_name,
        phone: res.phone,
        avater: res.avater
      }
    }

    return result
  }

  /**
   * 登录
   * @param {*} 用户信息 
   * @returns 
   */
  async h5Login ({
    username,
    password
  }) {
    const {
      ctx,
      app
    } = this
    const user = await this.find('UsersH5', username)
    let result = {}
    if (user) {
      const encryptPassword = ctx.helper.handleEnCrypt(password, app.config.security.cryptoKey)
      if (encryptPassword === user.password) {
        // 生成token
        const token = await ctx.service.accessToken.createToken({
          username,
          password
        })
        result = {
          data: {
            token,
            userInfo: {
              username: user.user_name,
              phone: user.phone,
              avater: user.avater
            }
          }
        }
      } else {
        result.code = 4003
        result.msg = '用户名或密码不正确'
      }
    } else {
      result.code = 4004
      result.msg = '用户不存在'
    }

    return result
  }

  /**
   * 管理后台登录
   */
  async adminLogin ({
    username,
    password
  }) {
    const {
      ctx,
      app
    } = this
    const user = await this.find('UsersAdmin', username)
    const result = {}

    if (user) {
      const encryptPassword = ctx.helper.handleEnCrypt(password, app.config.security.cryptoKey)
      if (user.password === encryptPassword) {
        const token = await ctx.service.accessToken.createToken({
          username,
          password
        })
        result.token = token
        result.userInfo = {
          username: user.user_name,
          phone: user.phone,
          avater: user.avater
        }
      } else {
        result.code = 4003
        result.msg = '用户不存在'
      }
    } else {
      result.code = 4004
      result.msg = '用户不存在'
    }

    return result
  }
}

module.exports = UserService